package top.yoahh.security;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import top.yoahh.security.config.*;
import top.yoahh.security.service.UserService;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * security的所有的基础配置
 */
@Slf4j
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoderConfig passwordEncoderConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private FilterInvocationSecurityMetadataSourceConfig filterInvocationSecurityMetadataSourceConfig;


    @Autowired
    private AccessDecisionManagerConfig accessDecisionManagerConfig;

    @Autowired
    private AuthenticationSuccessHandlerConfig authenticationSuccessHandlerConfig;

    @Autowired
    private AuthenticationEntryPointConfig authenticationEntryPointConfig;

    @Autowired
    private AuthenticationFailureHandlerConfig authenticationFailureHandlerConfig;

    @Autowired
    private AccessDeniedHandlerConfig accessDeniedHandlerConfig;

    public static final String[] ANONYMOUS_ACCESS_ADDRESS = {
            "/swagger-resources/**",
            "/doc.html",
            "/v2/api-docs/**",
            "/webjars/**",
            "/sysDict/**"
    };

    @Bean
    public PasswordEncoder passwordEncoder() {
        return passwordEncoderConfig;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoderConfig);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS);
        web.ignoring().antMatchers(ANONYMOUS_ACCESS_ADDRESS);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("========>加载Spring Security的基础配置：MyWebSecurityConfig.configure(HttpSecurity)");
        // authorizeRequests()方法表示开启HttpSecurity认证
        http.authorizeRequests()
                // HttpSecurity配置，可以通过URL获取对应的角色信息
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(filterInvocationSecurityMetadataSourceConfig);
                        object.setAccessDecisionManager(accessDecisionManagerConfig);
                        return object;
                    }
                });
        http.formLogin()
                // 登录请求接口，默认为 "/login" 接口
                .loginProcessingUrl("/login")
                // 登录参数-用户名
                .usernameParameter("username")
                // 登录参数-密码
                .passwordParameter("password")
                // 登录成功回调函数-返回登陆成功的JSON信息
                .successHandler(authenticationSuccessHandlerConfig)
                // 登录失败回调函数-返回登陆失败的JSON信息
                .failureHandler(authenticationFailureHandlerConfig)
                // 和登录相关的接口都不需要认证即可访问
                .permitAll();

        http.logout()
                // 配置注销登录请求URL，默认为 "/logout"
                .logoutUrl("/logout")
                // 是否清除身份认证信息，默认为true，表示清除
                .clearAuthentication(true)
                // 是否使session失效，默认为true
                .invalidateHttpSession(true)
                // 删除指定的Cookie信息，可以传入多个key
                .deleteCookies("JSESSIONID")
                // 注销回调函数，可以处理数据清除工作
                .addLogoutHandler((request, response, authentication) -> {
                    System.out.println("-----logout_handler----->");
                })
                // 注销成功回调函数
                .logoutSuccessHandler((request, response, authentication) -> {
                    System.out.println("-----logout_success----->");
                    // 注销成功后重定向到登录页
                    // response.sendRedirect("/login");
                });
        // 关闭csrf
        http.csrf().disable();

        // 用户未登录处理器
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPointConfig);

        // 权限不足处理器
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandlerConfig);

    }
}
